import java.util.concurrent.PriorityBlockingQueue;

public class Timer {
    static class Task implements Comparable<Task>{
        private Runnable command;
        private long time;

        public Task(Runnable command, long time){
            this.command = command;
            // time 中存的时间是绝对时间，超过这个时间的任务就应该执行
            this.time = System.currentTimeMillis() + time;   // 确定了当前
        }

        @Override
        public int compareTo(Task o) {
            return (int)(time - o.time);
        }

        public void run(){
            command.run();
        }
    }

    // 核心结构
    private PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
    // 存在的意义是避免woeker 线程 出现忙等的情况
    private Object mailBox = new Object();

    class Worker extends Thread{
        public void run(){
            while(true){
                try{
                    //Task task = queue.peek();
                    // 最为方法写成take的时候会标红
                    Task task = queue.take();
                    long curTime = System.currentTimeMillis();
                    if(task.time > curTime){ // 时间还没到，就把任务再塞回去
                        queue.put(task);
                        synchronized (mailBox){
                            // 指定等待时间wait
                            mailBox.wait(task.time - curTime);
                        }
                    }else{
                        // 时间到了 ，可以执行任务
                        task.run();
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                    break;
                }
            }
        }

    }

    public Timer(){
        Worker worker = new Worker();
        worker.start();   // 这里稍微注意一下，这里线程是通过继承Thread然后重写run的写法
    }

    public void schedule(Runnable command, long after){
        Task task = new Task(command, after);
        queue.offer(task);
        synchronized(mailBox){
            mailBox.notify();
        }
    }

    public static void main(String[] args) {
        Timer timer = new Timer();
        Runnable command = new Runnable() {
            @Override
            public void run() {
                System.out.println("我来了");
                timer.schedule(this, 3000);
            }
        };
        timer.schedule(command, 3000);

    }

}
